package repository

import (
	"sen-golang-study/go_game_study/hero_story_go_server/gateway_server/internal/domain/entity"
	"sync"
)

type SessionRepository struct {
	sessions *sync.Map
}

func NewSessionRepository() *SessionRepository {
	return &SessionRepository{
		sessions: &sync.Map{},
	}
}

func (r *SessionRepository) Save(session *entity.UserSession) error {
	r.sessions.Store(session.GetSessionID(), session)
	return nil
}

func (r *SessionRepository) FindByID(sessionID uint32) (*entity.UserSession, error) {
	if sessionID == 0 {
		return nil, nil
	}

	value, ok := r.sessions.Load(sessionID)
	if !ok {
		return nil, nil
	}

	return value.(*entity.UserSession), nil
}

func (r *SessionRepository) Delete(sessionID uint32) error {
	r.sessions.Delete(sessionID)
	return nil
}

func (r *SessionRepository) FindByUserID(userID uint32) (*entity.UserSession, error) {
	var result *entity.UserSession
	r.sessions.Range(func(key, value interface{}) bool {
		session := value.(*entity.UserSession)
		if session.GetUserID() == userID {
			result = session
			return false
		}
		return true
	})
	return result, nil
}
